package org.tio.examples.httpImpl.server;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
    
    private ByteBuffer readByteBuffer = ByteBuffer.allocate(2048);
    
    private AsynchronousSocketChannel async = null;
    
    private CompletionHandler com;
    
    public ReadCompletionHandler(AsynchronousSocketChannel asynchronousSocketChannel) {
		super();
		this.async = asynchronousSocketChannel;
		this.com = new WriteCompletionHandler();
	}

	@Override
    public void completed(Integer result, ByteBuffer attachment) {
//    	System.out.println(result);
    	AsynchronousSocketChannel asynchronousSocketChannel = async;
        if (result > 0) {
        	int i = 0;
        	byte[] b = new byte[attachment.capacity()];
        	attachment.flip();
            while(attachment.hasRemaining()){
                b[i++] = attachment.get();
            }
            try {
				System.out.print(new String(b,"utf-8"));
				if(asynchronousSocketChannel!=null){
		            boolean isopen = asynchronousSocketChannel.isOpen();
		            if(isopen){
		                ByteBuffer bytes = ByteBuffer.allocate(2048);
		                
		                asynchronousSocketChannel.write(bytes, bytes, com);
		            }
		        }
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
        } else if (result == 0) {
            return;
        } else if (result < 0) {
            
            return;
        }
        if(asynchronousSocketChannel!=null){
        	boolean isopen = asynchronousSocketChannel.isOpen();
        	if(isopen){
        		readByteBuffer.position(0);
        		readByteBuffer.limit(readByteBuffer.capacity());
        		asynchronousSocketChannel.read(readByteBuffer, readByteBuffer, this);
        	}
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        
    }
    
}
